package com.onelap.bls.treadmillcalibration.activity.calibration;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.google.gson.Gson;
import com.onelap.bls.treadmillcalibration.R;
import com.onelap.bls.treadmillcalibration.activity.index.DeviceBean;
import com.onelap.bls.treadmillcalibration.service.UartService;
import com.onelap.bls.treadmillcalibration.utils.BLeUtil;
import com.onelap.bls.treadmillcalibration.utils.TitleBar;

import java.io.UnsupportedEncodingException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_DATA_AVAILABLE;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_GATT_CONNECTED;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_GATT_DISCONNECTED;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.ACTION_GATT_SERVICES_DISCOVERED;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.DEVICE_DOES_NOT_SUPPORT_UART;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.EXTRA_BATTERY_LEVEL;
import static com.onelap.bls.treadmillcalibration.utils.BLeUtil.Params.EXTRA_DATA;

public class CalibrationActivity extends BaseActivity implements BLeUtil.BleUtilCallback {
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_electric)
    TextView tvElectric;
    @BindView(R.id.one_et_speed)
    EditText oneEtSpeed;
    @BindView(R.id.one_btn_confirm)
    Button oneBtnConfirm;
    @BindView(R.id.one_tv_show_1)
    TextView oneTvShow1;
    //    @BindView(R.id.one_tv_show_2)
//    TextView oneTvShow2;
    @BindView(R.id.tl_test_one)
    LinearLayout tlTestOne;
    @BindView(R.id.two_et_1)
    EditText twoEt1;
    @BindView(R.id.two_btn_1)
    Button twoBtn1;
    @BindView(R.id.two_iv_1)
    ImageView twoIv1;
    @BindView(R.id.two_et_2)
    EditText twoEt2;
    @BindView(R.id.two_btn_2)
    Button twoBtn2;
    @BindView(R.id.two_iv_2)
    ImageView twoIv2;
    @BindView(R.id.two_et_3)
    EditText twoEt3;
    @BindView(R.id.two_btn_3)
    Button twoBtn3;
    @BindView(R.id.two_iv_3)
    ImageView twoIv3;
    @BindView(R.id.tl_test_two)
    LinearLayout tlTestTwo;
    @BindView(R.id.two_btn_start)
    Button twoBtnStart;
    @BindView(R.id.two_btn_over)
    Button twoBtnOver;
    @BindView(R.id.two_tv_1)
    TextView twoTv1;

    private String calibrationType = "ONE";
    //private BluetoothDevice bluetoothDevice;
    private DeviceBean deviceBean;
    private UartService bluetoothLeService;
    private BLeUtil bLeUtil;
    private int intSpeedV1;  //跑步机速度

    private boolean isStartPoDu = false;
    private boolean isOverPoDu = false;
    private int writePoDu = 0;  //跑步机坡度的填写状态
    private ProgressDialog progressDialog;


    @Override
    protected void initParams() {
        super.initParams();
        calibrationType = getIntent().getStringExtra("CalibrationType");
        deviceBean = new Gson().fromJson(getIntent().getStringExtra("DeviceBean"), DeviceBean.class);
        bLeUtil = new BLeUtil(this);

        bLeUtil.bindBleService(getActivity(), UartService.class,
                ACTION_GATT_CONNECTED,
                ACTION_GATT_DISCONNECTED,
                ACTION_GATT_SERVICES_DISCOVERED,
                ACTION_DATA_AVAILABLE,
                EXTRA_BATTERY_LEVEL,
                DEVICE_DOES_NOT_SUPPORT_UART);
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_calibration;
    }

    @Override
    protected void initFvb() {
        super.initFvb();
        ButterKnife.bind(this);
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        TitleBar titleBar = findViewById(R.id.tb_title_bar);
        titleBar.setTitle(calibrationType.equals("ONE") ? "跑步机轮径校准" : "跑步机坡度校准");
        titleBar.setBackgroundColor(Color.BLACK);
        titleBar.setTitleColor(Color.WHITE);
        titleBar.setLeftImageResource(R.mipmap.a2);
        titleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                getActivity().finish();
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        tvId.setText("设备ID：".concat(deviceBean.getDevice().getName()));
        tlTestOne.setVisibility(calibrationType.equals("ONE") ? View.VISIBLE : View.GONE);
        tlTestTwo.setVisibility(calibrationType.equals("TWO") ? View.VISIBLE : View.GONE);

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("连接中，请稍等......");
        progressDialog.setCancelable(false);
        progressDialog.show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                progressDialog.cancel();
            }
        }, 1000);
    }

    @OnClick(R.id.one_btn_confirm)
    public void onOneBtnConfirmClicked() {
        String strSpeedV1 = oneEtSpeed.getText().toString().trim();
        if (strSpeedV1.equals("")) {
            ToastUtils.showShort("请填写跑步机速度");
            return;
        }
        if (strSpeedV1.length() == 1) {
            strSpeedV1 = "0".concat(strSpeedV1);
        }
        intSpeedV1 = Integer.parseInt(strSpeedV1);
        try {
            bluetoothLeService.writeRXCharacteristicUTF_8("88".concat(strSpeedV1));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.two_btn_1)
    public void onTwoBtn1Clicked() {
        String value = twoEt1.getText().toString().trim();

        if (!isStartPoDu) {
            ToastUtils.showShort("请点击“开始校准数据”按钮");
            return;
        }

        if (value.equals("")) {
            ToastUtils.showShort("请输入状态1的坡度");
            return;
        }
        if (value.length() == 1) {
            value = "0".concat(value);
        }
        value = "80".concat(value);
        try {
            bluetoothLeService.writeRXCharacteristicUTF_8(value);
            writePoDu = 1;
            twoBtn1.setEnabled(false);
            twoIv1.setVisibility(View.VISIBLE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.two_btn_2)
    public void onTwoBtn2Clicked() {
        String value = twoEt2.getText().toString().trim();

        if (writePoDu != 1) {
            ToastUtils.showShort("请发送状态1数据");
            return;
        }

        if (value.equals("")) {
            ToastUtils.showShort("请输入状态2的坡度");
            return;
        }
        if (value.length() == 1) {
            value = "0".concat(value);
        }
        value = "80".concat(value);
        try {
            bluetoothLeService.writeRXCharacteristicUTF_8(value);
            writePoDu = 2;
            twoBtn2.setEnabled(false);
            twoIv2.setVisibility(View.VISIBLE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.two_btn_3)
    public void onTwoBtn3Clicked() {
        String value = twoEt3.getText().toString().trim();

        if (writePoDu != 2) {
            ToastUtils.showShort("请发送状态2数据");
            return;
        }

        if (value.equals("")) {
            ToastUtils.showShort("请输入状态3的坡度");
            return;
        }
        if (value.length() == 1) {
            value = "0".concat(value);
        }
        value = "80".concat(value);
        try {
            bluetoothLeService.writeRXCharacteristicUTF_8(value);
            writePoDu = 3;
            twoBtn3.setEnabled(false);
            twoIv3.setVisibility(View.VISIBLE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.two_btn_start)
    public void onTwoBtnStartClicked() {
        try {
            bluetoothLeService.writeRXCharacteristicUTF_8("80AA");
            isStartPoDu = true;
            twoBtnStart.setEnabled(false);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.two_btn_over)
    public void onTwoBtnOverClicked() {
        if (writePoDu != 3) {
            ToastUtils.showShort("请发送状态3数据");
            return;
        }
        try {
            bluetoothLeService.writeRXCharacteristicUTF_8("80BB");
            isOverPoDu = true;
            twoBtnOver.setEnabled(false);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBleUtilCallback(int status, BluetoothDevice device, int rssi, byte[] scanRecord, IBinder rawBinder, Intent intent) {
        switch (status) {
            case BLeUtil.STATUS_SERVICE_CONNECTED:
                bluetoothLeService = ((UartService.LocalBinder) rawBinder).getService();
                LogUtils.i("onServiceConnected mService=", bluetoothLeService);
                if (!bluetoothLeService.initialize()) {
                    LogUtils.i("onServiceConnected mService=", "Unable to initialize Bluetooth");
                    AppUtils.exitApp();
                }
                bluetoothLeService.connect(deviceBean.getDevice().getAddress());
                break;
            case BLeUtil.STATUS_SERVICE_DISCONNECTED:
                bluetoothLeService = null;
                break;
            case BLeUtil.STATUS_ACTION_GATT_SERVICES_DISCOVERED:
                break;
            case BLeUtil.STATUS_ACTION_DATA_AVAILABLE:
                byte[] txValue = intent.getByteArrayExtra(EXTRA_DATA);
                String text = null;
                try {
                    text = new String(txValue, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                LogUtils.i("ReceiveData", text);
                if (calibrationType.equals("ONE") && text != null) {
                    if (text.equals("88GG")) {
                        LogUtils.i("设备接收到速度信息");
                    } else if (text.startsWith("88")) {
                        String strRotationRate = text.substring(2);
                        oneTvShow1.setText(strRotationRate.concat("KM/H"));
                    }

                } else if (calibrationType.equals("TWO") && text != null) {
                    if (text.equals("80GG")) {
                        LogUtils.i("设备接收到坡度信息");
                    } else if (text.startsWith("80")) {
                        String temp = text.substring(2);
                        twoTv1.setText(temp.concat("度"));
                    }
                }
        }
    }

    @Override
    protected void initOnDestroy() {
        super.initOnDestroy();
    }
}
